package com.gtmonitor.graphics;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.Html;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.gtmonitor.GTmonitorActivity;
import com.gtmonitor.GTmonitorService;
import com.gtmonitor.JNIInterface;
import com.gtmonitor.Preferences;
import com.gtmonitor.R;
import com.gtmonitor.network.NetworkView;
import com.gtmonitor.processes.MemoryView;
import com.gtmonitor.processes.ProcessView;
import com.gtmonitor.storage.StorageView;

public class GraphicsActivity extends Activity {
    
    private final static String TAG = "GTmonitor";
    public static JNIInterface JNILibrary = JNIInterface.getInstance();
    public static TextView CPULoadValue = null;
    public static TextView memoryUsageValue = null;
    public static TextView storageNbrValue = null;
    public static TextView networkValue = null;
    public static ProcessView processGraph = null;
    public static MemoryView memoryGraph = null;
    public static StorageView storageGraph = null;
    public static NetworkView networkGraph = null;
    public static CheckBox freezeCheckBox = null;
    public static CheckBox logCheckBox = null;
    public static final Handler uiHandler = new Handler();
    public static boolean freeze = false;
    public static String[] storageNames;
    public static int numOfStorages;
    public static boolean[] hide;
    public static final int ctxMenuCPUGroup = 0;
    public static final int ctxMenuMemGroup = 1;
    public static final int ctxMenuDskGroup = 2;
    public static final int ctxMenuNetGroup = 3;
    public static boolean loggable = true;
    public static int screenWidth = 0;
    /*
    public static SurfaceHolder storageSurfaceHolder;
    public static SurfaceHolder CPUSurfaceHolder;
    public static SurfaceHolder memorySurfaceHolder;
    public static SurfaceHolder networkSurfaceHolder;
    public static Canvas storageCanvas;
    public static Canvas processCanvas;
    public static Canvas memoryCanvas;
    */
    
    public Runnable uiRunnable = new Runnable() {
        public void run() {
            if (!freeze) {
                CPULoadValue.setText(GTmonitorService.CPULoadText);
                memoryUsageValue.setText(GTmonitorService.memUsageText);
                storageNbrValue.setText(GTmonitorService.storageInfoText);
                networkValue.setText(Html.fromHtml(GTmonitorService.networkInfoText.toString()));
               
                processGraph.invalidate();
                memoryGraph.invalidate();
                storageGraph.invalidate();
                networkGraph.invalidate();

                uiHandler.postDelayed(this, 1000);
             }
        }
    };
    
    /*public void updateLoggable() {
        loggable =  !GTmonitorService.powerSaving &&
                    GTmonitorActivity.externalStorageWriteable;
    }
    */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.graphicslayout);
        freeze = false;
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
        if (settings.getBoolean(Preferences.PREF_POWERSAVINGMODE, false)) {
            GTmonitorService.powerSaving = true;
        } else GTmonitorService.powerSaving = false;
        //updateLoggable();
        if (GTmonitorActivity.externalStorageWriteable) {
            loggable = true;
        } else loggable = false;
        CPULoadValue = (TextView)findViewById(R.id.CPUUsageValue);
        processGraph = (ProcessView)findViewById(R.id.processGraph);
        
        memoryUsageValue = (TextView)findViewById(R.id.memoryUsageValue);
        memoryGraph = (MemoryView)findViewById(R.id.memoryGraph);
        
        storageNbrValue = (TextView)findViewById(R.id.storageNbrValue);
        storageGraph = (StorageView)findViewById(R.id.storageGraph);
               
        networkGraph = (NetworkView)findViewById(R.id.networkGraph);
        networkValue = (TextView)findViewById(R.id.networkValue);
        
        freezeCheckBox = (CheckBox)findViewById(R.id.freezeCheckBox);
        freezeCheckBox.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if(freeze) {
                    freeze = false;
                    uiHandler.post(uiRunnable);
                }
                else freeze = true;
            }
        });
        logCheckBox = (CheckBox)findViewById(R.id.checkBoxLogging);
        logCheckBox.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (logCheckBox.isChecked()) {
                    GTmonitorService.turnOnAllLogging = true;
                    GTmonitorService.CPULogOn = true;
                    GTmonitorService.storageLogOn = true;
                    GTmonitorService.memoryLogOn = true;
                    GTmonitorService.networkLogOn = true;
                    JNILibrary.setCPULogging(true);
                    JNILibrary.setMemLogging(true);
                    JNILibrary.setDskLogging(true);
                    JNILibrary.setNetLogging(true);
                } else {
                    GTmonitorService.turnOnAllLogging = false;
                    GTmonitorService.CPULogOn = false;
                    GTmonitorService.storageLogOn = false;
                    GTmonitorService.memoryLogOn = false;
                    GTmonitorService.networkLogOn = false;
                    JNILibrary.setCPULogging(false);
                    JNILibrary.setMemLogging(false);
                    JNILibrary.setDskLogging(false);
                    JNILibrary.setNetLogging(false);
                }
            }});
        logCheckBox.setEnabled(loggable);
        logCheckBox.setChecked(GTmonitorService.turnOnAllLogging);

        registerForContextMenu(findViewById(R.id.processGraph));
        registerForContextMenu(findViewById(R.id.memoryGraph));
        registerForContextMenu(findViewById(R.id.storageGraph));
        registerForContextMenu(findViewById(R.id.networkGraph));
        
        uiHandler.post(uiRunnable);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, 
                                    View v, 
                                    ContextMenu.ContextMenuInfo menuInfo) {
        MenuItem item;
        if (v.getId() == R.id.processGraph) {
            menu.setHeaderTitle(R.string.contextMenuCPUTitle);
            
            // Start/Stop Logging
            if (!GTmonitorService.CPULogOn) {
                item = menu.add(ctxMenuCPUGroup, 0, Menu.NONE, 
                                R.string.contextMenuLogOnItem);
                item.setEnabled(loggable);
            }
            else item = menu.add(ctxMenuCPUGroup, 0, Menu.NONE, 
                                R.string.contextMenuLogOffItem);
            
            // Include/Exclude Self
            if (!GTmonitorService.excludeSelfCPULoad) {
                item = menu.add(ctxMenuCPUGroup, 1, Menu.NONE, 
                                R.string.excludeSelfCPULoad);
            } else item = menu.add(ctxMenuCPUGroup, 1, Menu.NONE, 
                                R.string.includeSelfCPULoad);
            
        } else if (v.getId() == R.id.memoryGraph) {
            menu.setHeaderTitle(R.string.contextMenuMemTitle);
            
            // Start/Stop Logging
            if (!GTmonitorService.memoryLogOn) {
                item = menu.add(ctxMenuMemGroup, 0, Menu.NONE, 
                                R.string.contextMenuLogOnItem);
                item.setEnabled(loggable);
            }
            else item = menu.add(ctxMenuMemGroup, 0, Menu.NONE, 
                                R.string.contextMenuLogOffItem);

        } else if (v.getId() == R.id.storageGraph) {
            menu.setHeaderTitle(R.string.contextMenuStorageTitle);
            
            // Start/Stop Logging
            if (!GTmonitorService.storageLogOn) {
                item = menu.add(ctxMenuDskGroup, 0, Menu.NONE, 
                                R.string.contextMenuLogOnItem);
                item.setEnabled(loggable);
            }
            else item = menu.add(ctxMenuDskGroup, 0, Menu.NONE, 
                                R.string.contextMenuLogOffItem);
            
            // Each storage device
            int nos = GTmonitorService.numOfStorage;
            if (nos > 0) {
                storageNames = GTmonitorService.storageNames;
                for (int i=0; i<nos; ++i) {
                    addMenuItem(menu, ctxMenuDskGroup, i+1, storageNames[i], true);
                }
            }
        } else if (v.getId() == R.id.networkGraph) {
            menu.setHeaderTitle(R.string.contextMenuNetTitle);
            
            // Start/Stop Logging
            if (!GTmonitorService.networkLogOn) {
                item = menu.add(ctxMenuNetGroup, 0, Menu.NONE, 
                                R.string.contextMenuLogOnItem);
                item.setEnabled(loggable);
            }
            else item = menu.add(ctxMenuNetGroup, 0, Menu.NONE, 
                                R.string.contextMenuLogOffItem);
        } 
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        int groupId = item.getGroupId();
         
        // CPU
        if (groupId == ctxMenuCPUGroup) {
            int itemId = item.getItemId();
            if (itemId == 0) {
                if (!GTmonitorService.CPULogOn) 
                    Toast.makeText(this, R.string.CPULogOnToast, 
                            Toast.LENGTH_SHORT).show(); 
                else 
                    Toast.makeText(this, R.string.CPULogOffToast, 
                            Toast.LENGTH_SHORT).show();
                GTmonitorService.CPULogOn = !GTmonitorService.CPULogOn;
                JNILibrary.setCPULogging(GTmonitorService.CPULogOn && loggable);
            } else if (itemId == 1) {
                if (!GTmonitorService.excludeSelfCPULoad)
                    Toast.makeText(this, R.string.excludeSelfCPUToast, 
                            Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(this, R.string.includeSelfCPUToast, 
                            Toast.LENGTH_SHORT).show();
                GTmonitorService.excludeSelfCPULoad 
                    = !GTmonitorService.excludeSelfCPULoad;
            }
        } 
        // Memory
        else if (groupId == ctxMenuMemGroup) {
            if (!GTmonitorService.memoryLogOn) 
                Toast.makeText(this, R.string.memoryLogOnToast, 
                        Toast.LENGTH_SHORT).show();
            else Toast.makeText(this, R.string.memoryLogOffToast, 
                    Toast.LENGTH_SHORT).show();
            GTmonitorService.memoryLogOn = !GTmonitorService.memoryLogOn;
            JNILibrary.setMemLogging(GTmonitorService.memoryLogOn && loggable);
        } 
        // Storage Device
        else if (groupId == ctxMenuDskGroup) {
            int itemId = item.getItemId();
            if (itemId == 0) {
                if (!GTmonitorService.storageLogOn) 
                    Toast.makeText(this, R.string.storageLogOnToast, 
                            Toast.LENGTH_SHORT).show();
                else Toast.makeText(this, R.string.storageLogOffToast, 
                        Toast.LENGTH_SHORT).show();
                GTmonitorService.storageLogOn = !GTmonitorService.storageLogOn;
                JNILibrary.setDskLogging(GTmonitorService.storageLogOn && loggable);
            } else {
                --itemId; // item id 0 is for start/stop logging
                Toast.makeText(this, "Showing utility of " + storageNames[itemId], 
                        Toast.LENGTH_SHORT).show(); 
                hide = StorageView.hide;
                hide[itemId] = false;
                GTmonitorService.storageOnBar = itemId;
                numOfStorages = GTmonitorService.numOfStorage;
                for (int i=0; i<numOfStorages; ++i) if (i != itemId)
                    hide[i] = true;
            }
        } else if (groupId == ctxMenuNetGroup) {
            if (!GTmonitorService.networkLogOn) 
                Toast.makeText(this, R.string.networkLogOnToast, 
                        Toast.LENGTH_SHORT).show();
            else Toast.makeText(this, R.string.networkLogOffToast, 
                    Toast.LENGTH_SHORT).show();
            GTmonitorService.networkLogOn = !GTmonitorService.networkLogOn;
            JNILibrary.setNetLogging(GTmonitorService.networkLogOn && loggable);
        }
        return true;
    }
    
    public void addMenuItem(ContextMenu menu, int groupId, int itemId, 
                            String itemName, boolean checkable) {
        MenuItem item = menu.add(groupId, itemId, Menu.NONE, itemName);
        item.setEnabled(checkable);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu optionMenu) {
        super.onCreateOptionsMenu(optionMenu);

        optionMenu.add(0, 0, 0, R.string.optionMenuOptionText);
        //optionMenu.add(0, 1, 0, R.string.optionMenuHelpText);
        optionMenu.add(0, 5, 1, R.string.ExitText);

        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
        case 0:
            Intent launchPreferencesIntent 
                = new Intent().setClass(this, Preferences.class);
            startActivityForResult(launchPreferencesIntent, 0);
            break;
        case 1:
            Toast.makeText(this, "TODO: Add Help Info", Toast.LENGTH_SHORT).show();
            break;
        case 5:
            if(GTmonitorService.getInstance() != null)
                GTmonitorService.getInstance().stopSelf();
            JNILibrary.exitApp();
            GTmonitorService.cancelAllNotifications();
            android.os.Process.killProcess(android.os.Process.myPid());
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    public void onPause() {
        uiHandler.removeCallbacks(uiRunnable);
        super.onPause();
    }
    
    @Override
    protected void onResume() {
        if (!freeze) {
            uiHandler.post(uiRunnable);
        }
        if (GTmonitorActivity.externalStorageWriteable) {
            loggable = true;
        } else loggable = false;
        logCheckBox.setEnabled(loggable);
        super.onResume();
    }

    private void restorePreferences() {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
        if (settings.getBoolean(Preferences.PREF_POWERSAVINGMODE, false)) {
            GTmonitorService.powerSaving = true;
        } else {
            if(GTmonitorService.getInstance() == null) {
                startService(new Intent(this, GTmonitorService.class));
            }
            else {
                GTmonitorService.getInstance().resume(settings);
            }
        }
        GTmonitorService service = GTmonitorService.getInstance();
        service.restorePreferencesStatusBar(settings);        
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        restorePreferences();
        //updateLoggable();
        logCheckBox.setEnabled(loggable);
        logCheckBox.setChecked(GTmonitorService.turnOnAllLogging);
        super.onActivityResult(requestCode, resultCode, data);
    }
}


